package com.yunchang.open.iploaction.parser.ipip;

import com.yunchang.open.iploaction.Location;
import com.yunchang.open.iploaction.parser.IPv4Parser;
import com.yunchang.open.iploaction.utils.IOUtil;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.Arrays;

/**
 * ipip.net提供的ipv4免费库的解析类。
 * Created by jasontujun on 2019/6/25.
 *
 * @see <a href="https://www.ipip.net/free_download/">ip库下载地址</a>
 */
public class IpipParser implements IPv4Parser {

    private byte[] data;
    private long indexSize;

    private static long bytesToLong(byte a, byte b, byte c, byte d) {
        return int2long((((a & 0xff) << 24) | ((b & 0xff) << 16) | ((c & 0xff) << 8) | (d & 0xff)));
    }

    private static long int2long(int i) {
        long l = i & 0x7fffffffL;
        if (i < 0) {
            l |= 0x080000000L;
        }
        return l;
    }

    private static int str2Ip(String ip) {
        String[] ss = ip.split("\\.");
        int a, b, c, d;
        a = Integer.parseInt(ss[0]);
        b = Integer.parseInt(ss[1]);
        c = Integer.parseInt(ss[2]);
        d = Integer.parseInt(ss[3]);
        return (a << 24) | (b << 16) | (c << 8) | d;
    }

    @Override
    public IPv4Parser init(InputStream inputStream) throws Exception {
        data = IOUtil.read(inputStream);
        indexSize = bytesToLong(data[0], data[1], data[2], data[3]);
        return this;
    }

    @Override
    public int getPriority() {
        return DEFAULT_PRIORITY;
    }

    @Override
    public Location findIpv4Location(String ipv4) {
        if (data == null) {
            return null;
        }

        long val = int2long(str2Ip(ipv4));
        int start = 262148;
        int low = 0;
        int mid = 0;
        int high = new Long((indexSize - 262144 - 262148) / 9).intValue() - 1;
        int pos = 0;
        while (low <= high) {
            mid = new Double((low + high) / 2).intValue();
            pos = mid * 9;

            long s = 0;
            if (mid > 0) {
                int pos1 = (mid - 1) * 9;
                s = bytesToLong(data[start + pos1], data[start + pos1 + 1], data[start + pos1 + 2], data[start + pos1 + 3]);
            }

            long end = bytesToLong(data[start + pos], data[start + pos + 1], data[start + pos + 2], data[start + pos + 3]);
            if (val > end) {
                low = mid + 1;
            } else if (val < s) {
                high = mid - 1;
            } else {

                byte b = 0;
                long off = bytesToLong(b, data[start + pos + 6], data[start + pos + 5], data[start + pos + 4]);
                long len = bytesToLong(b, b, data[start + pos + 7], data[start + pos + 8]);

                int offset = new Long(off - 262144 + indexSize).intValue();

                byte[] loc = Arrays.copyOfRange(data, offset, offset + new Long(len).intValue());

                String[] locationArray = new String(loc, Charset.forName("UTF-8")).split("\t", -1);
                if (locationArray.length > 0) {
                    Location location = new Location();
                    String country = locationArray[0];
                    String province = locationArray[1];
                    //不是中国就是国外
                    if ("中国".equals(country)) {
                        location.setCountry(country);
                        //省份也是中国的就不存了
                        if (!"中国".equals(province)) {
                            location.setProvince(province);
                        }
                        if (locationArray.length >= 3) {
                            location.setCity(locationArray[2]);
                        }
                    } else {
                        if (province.contains("骨干网") || province.contains("GOOGLE") || province.contains("COM")
                                || province.contains("局域网") || province.contains("保留地址")) {
                            //无效的
                        } else {
                            //国外的
                            location.setProvince(province);
                            location.setCountry("海外");
                        }
                    }
                    return location;
                }
            }
        }
        return null;
    }
}
